package com.netafull;

import java.util.ArrayList;
import java.util.List;

import com.netafull.adapter.CategoryAdapter;
import com.netafull.adapter.HomePageAdapter;
import com.netafull.analyze.AnalyzeXMLForCategory;
import com.netafull.analyze.AnalyzeXMLForCategoryTitleCount;
import com.netafull.analyze.AnalyzeXMLForHomepage;
import com.netafull.analyze.Category;
import com.netafull.analyze.CategoryCount;
import com.netafull.analyze.News;
import com.netafull.db.CategoryService;
import com.netafull.util.CloseUtil;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/*
 * category_id
 */
public class CategoryPage extends ShowAdActivity {
	String path;// 首次请求的url地址
	String getCategoryUrl;// 首次请求的url地址
	ImageButton btn_category_menu;
	ImageButton btn_category_about;
	ListView listView;
	TextView tv_title;
	//添加popuWindow*********************************
	PopupWindow menuWindow;
	private boolean menu_display = false;
	LayoutInflater inflater;
	View layout;
	ImageButton category_close;//PopuWindow页面左右两个按键
	ImageButton category_refresh;
	
	ListView category_listview;
	//添加popuWindow*********************************
	Handler handler;
	View progress;
	View category_progress;
	
	CategoryService dbService;//数据库操作
	

	private List<News> list = new ArrayList<News>();
	private List<News> moreNews = new ArrayList<News>();
	private List<Category> categoryList = new ArrayList<Category>();

	HomePageAdapter homePageAdapter;
	CategoryAdapter categoryAdapter;

	public static final int HOMEPAGE_REQUEST_OK = 1;// 请求成功
	public static final int HOMEPAGE_REQUEST_ERR = -1;// 请求失败

	AnalyzeXMLForHomepage analyzeXMLForHomepage;
	AnalyzeXMLForCategory analyzeXMLForCategory;
	AnalyzeXMLForCategoryTitleCount analyzeXMLForCategoryTitleCount;
	
	int category_id;
	String category_name;
	int category_count;
	//int category_count_temp;//从homepage传递过来的，第一次需要
	
	int categoryId;//这是从数据库中取得的category_id;
	
	View footerView;
	Button footerButton;
	LinearLayout footerProgress;
	
	Thread t;//刚进来的时候
	Thread t2;//在此页面点击category列表
	Thread t3;//footer
	
	int i = 0;
	
	boolean b = false;
	
	SharedPreferences sp;
	
	boolean flag = false;//标记数据库中是否有数据
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.categorypage);
		
		show();
		
		sp = getSharedPreferences("netafull",Context.MODE_PRIVATE);
		
		CloseUtil.activityList.add(CategoryPage.this);
		
		btn_category_menu = (ImageButton) findViewById(R.id.categorypage_button_left);
		btn_category_about = (ImageButton) findViewById(R.id.categorypage_button_right);
		tv_title = (TextView) findViewById(R.id.categorypage_title);
		dbService = new CategoryService(this);
		
		
		Intent intent = getIntent();
		categoryId = intent.getExtras().getInt("category_id");
		category_name = intent.getExtras().getString("category_name");
		//category_count_temp = intent.getExtras().getInt("category_count");
		
		
		
		tv_title.setText(category_name);
		path = getResources().getString(R.string.gettitlelist_category_url)+categoryId+"&device=Android";
		getCategoryUrl = getResources().getString(R.string.getcategory_url)+"?device=Android";
		analyzeXMLForHomepage = new AnalyzeXMLForHomepage();
		analyzeXMLForCategory = new AnalyzeXMLForCategory();
		analyzeXMLForCategoryTitleCount = new AnalyzeXMLForCategoryTitleCount();
		//listView = getListView();
		listView = (ListView) findViewById(R.id.categorypage_list);
		listView.setScrollbarFadingEnabled(true);
		
		//getTitleCountThread();//初始化category_count
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				b = true;
				if(position==list.size()){
					return;
				}
				News news = list.get(position);
				Intent intent = new Intent(CategoryPage.this, NewsContent.class);
				Bundle bundle = new Bundle();
				bundle.putString("title", news.getTitle());
				bundle.putInt("id", news.getId());
				intent.putExtras(bundle);
				startActivityForResult(intent,100);
			}
			
		});
		
		
		progress = findViewById(R.id.list_progress);
		
		
		LayoutInflater footerInflater = LayoutInflater.from(this);
		footerView = footerInflater.inflate(R.layout.homepage_listview_footer_more, null);
		footerButton = (Button) footerView.findViewById(R.id.homepage_footer_button);
		footerProgress = (LinearLayout) footerView.findViewById(R.id.footer_progress_linearlayout);
		if(category_count>30 && category_count<60){
			
			footerButton.setText("次の"+(category_count-30)+"件を読み込む？");
		} else {
			footerButton.setText("次の"+30+"件を読み込む？");
		}
		i = category_count;
		footerButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				System.out.println("点击了footer");
				footerButton.setVisibility(View.GONE);
				footerProgress.setVisibility(View.VISIBLE);
				footerProgress.setClickable(false);
				
				t3 = new Thread(){
					public void run(){
						String morePath = CategoryPage.this.getResources().getString(R.string.gettitlelist_more_url) + categoryId + "&offset=" + homePageAdapter.getCount()+"&device=Android";
						System.out.println("**********"+morePath);
						try {
							moreNews = analyzeXMLForHomepage.getRss(morePath);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						System.out.println("moreNews.size()="+moreNews.size());
//						if(moreNews.size() <0){
							Message message = new Message();
							message.what = 5;
							handler.sendMessage(message);
//						}
					}
				};
				t3.start();
			}
		});
		
		btn_category_menu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				openMenu();
			}
		});
		
		/*listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if()
			}
		});*/
		
		
		//****************************************************************
		inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
        layout = inflater.inflate(R.layout.popu, null);
        
        category_listview = (ListView)layout.findViewById(R.id.category_list);
        
        category_close = (ImageButton) layout.findViewById(R.id.category_button_left);
        category_refresh = (ImageButton) layout.findViewById(R.id.category_button_right);
        category_close.setOnClickListener(new OnClickListener(){
        	
			@Override
			public void onClick(View v) {
				category_close.setEnabled(false);
				category_close.setClickable(false);
				openMenu();
			}
        	
        });
        category_refresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//刷新category页面
				//Toast.makeText(HomePage.this, "刷新category页面", Toast.LENGTH_LONG).show();
				category_progress.setVisibility(View.VISIBLE);
				category_refresh.setEnabled(false);
				category_refresh.setClickable(false);
				category_close.setEnabled(false);
				category_close.setClickable(false);
				refreshCategoryList();
			}
		});
        //弹出menu 初始化
        menuWindow = new PopupWindow(layout,LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        
        category_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				b = true;
				listView.removeFooterView(footerView);
				if(t!=null && t.isAlive()){
					t.interrupt();
					System.out.println("线程正在运行，强行中断");
				}
				if(t2!=null && t2.isAlive()){
					t2.interrupt();
					System.out.println("线程正在运行，强行中断");
				}
				if(t3!=null && t3.isAlive()){
					t3.interrupt();
					System.out.println("线程正在运行，强行中断");
				}
				//homePageAdapter.items.clear();
				Category category = categoryList.get(position);
				tv_title.setText(category.getCategory_name());
				categoryId = category.getId();
				//System.out.println("点击Category某个项的时候，categoryId="+category.getId());
				
				//category_count = category.getTitle_count();
				openMenu();
				progress.setVisibility(View.VISIBLE);
				Intent intent = new Intent(CategoryPage.this, CategoryPage.class);
				Bundle b = new Bundle();
				b.putInt("category_id", category.getId());
				b.putString("category_name", category.getCategory_name());
				intent.putExtras(b);
				CategoryPage.this.startActivityForResult(intent,100);
				CategoryPage.this.finish();
				//homePageAdapter.items.clear();
				/*t2 = new Thread() {
					public void run() {
						Message msg = new Message();
						String tempUrl = getResources().getString(R.string.gettitlelist_category_url)+categoryId;
						try {
							list = analyzeXMLForHomepage.getRss(tempUrl);
							List<CategoryCount> temp = analyzeXMLForCategoryTitleCount.getRss(getResources().getString(R.string.gettitlelistcount_url222)+categoryId);
							category_count = temp.get(0).getCount();
							
							//footerButton.setText("more"+(category_count-i*30)+"");
							System.out.println("*********************list.size()="+list.size());
							if (list.size() != 0 && temp.size()!=0) {
								System.out.println("yes"+temp.get(0).getCategory()+","+temp.get(0).getCount());
								msg.what = HOMEPAGE_REQUEST_OK;
							} else {
								msg.what = HOMEPAGE_REQUEST_ERR;
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							msg.what = 9;//请求超时
						}
						
						handler.sendMessage(msg);
					};
				};
				t2.start();*/
			}
		});
        //****************************************************************
        btn_category_about.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				b = true;
				Intent intent = new Intent(CategoryPage.this, About.class);
				CategoryPage.this.startActivityForResult(intent,100);
			}
		});

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case HOMEPAGE_REQUEST_OK:// 请求成功
					progress.setVisibility(View.GONE);
					System.out.println("list.size()="+list.size()+",category_count="+category_count);
					if(homePageAdapter!=null){
						Log.e("caget", "list.size() = " +list.size() + "   total size = " + category_count + "fff = " +homePageAdapter.items.size());
						//if (homePageAdapter.items.size()<category_count) {
						if (list.size()<category_count) {
							Log.e("caget", "fffffffffffffffffffffffffff");
							listView.addFooterView(footerView);
							System.out.println("1.添加Footer");
							System.out.println("添加footer");
						} else {
							listView.removeFooterView(footerView);
						}
						
						if(list.size()<category_count){
							if(category_count-list.size()>=30){
								footerButton.setText("次の"+30+"件を読み込む？");
							} else {
								footerButton.setText("次の"+(category_count-list.size())+"件を読み込む？");
							}
							
						}
						
					} else {
						if(list.size()<category_count){
							listView.addFooterView(footerView);
							System.out.println("2.添加Footer");
							System.out.println("添加footer");
						} else {
							listView.removeFooterView(footerView);
						}
					} 
					if(homePageAdapter != null){
						//homePageAdapter.setCount(0);
						homePageAdapter.items.clear();
					}
					showList();// 显示数据内容
					System.out.println(list.size()+","+category_count);
					
					break;
				case HOMEPAGE_REQUEST_ERR:// 请求失败
					break;
				case 2:
					showCategoryList();
					//categoryList = null;
					category_refresh.setEnabled(true);
					category_refresh.setClickable(true);
					category_close.setEnabled(true);
					category_close.setClickable(true);
					break;
				case -2://刷新超时
					
					//categoryList = null;
					if(flag){
						showCategoryListFromDB();
					}else{
						category_progress.setVisibility(View.GONE);
						showNetBusy();
					}
					category_refresh.setEnabled(true);
					category_refresh.setClickable(true);
					category_close.setEnabled(true);
					category_close.setClickable(true);
					break;
				case 3://数据库中有数据
					showCategoryListFromDB();
					category_refresh.setEnabled(true);
					category_refresh.setClickable(true);
					category_close.setEnabled(true);
					category_close.setClickable(true);
					break;
				case 4://刷新成功
					refreshShowCategoryList();
					category_refresh.setEnabled(true);
					category_refresh.setClickable(true);
					category_close.setEnabled(true);
					category_close.setClickable(true);
					break;
				case 5://刷新成功
					
					System.out.println("点击了footer，开始更新UI"+category_count);
					homePageAdapter.items.addAll(moreNews);
					
					
					
					if(homePageAdapter.items.size() >= category_count){
						listView.removeFooterView(footerView);
					}
					homePageAdapter.setCount(homePageAdapter.getCount()+moreNews.size());
					if(moreNews.size()!=0){
						moreNews.clear();
					}
					homePageAdapter.notifyDataSetChanged();
					footerButton.setVisibility(View.VISIBLE);
					footerProgress.setVisibility(View.GONE);
					
					
					System.out.println(list.size()+"--->"+category_count);
					if(list.size()<category_count){
						if(category_count-list.size()>=30){
							footerButton.setText("次の"+30+"件を読み込む？");
						} else {
							footerButton.setText("次の"+(category_count-list.size())+"件を読み込む？");
						}
						
					}
					
					/*if(moreNews.size()!=0){
						homePageAdapter.items.addAll(moreNews);
						homePageAdapter.setCount(homePageAdapter.getCount()+10);
						homePageAdapter.notifyDataSetChanged();
					} else {
						listView.removeFooterView(footerView);
						Toast.makeText(CategoryPage.this, "**移除footer", Toast.LENGTH_SHORT).show();
					}*/
					
					break;
				case 9:
					//showNetBusy1();
					break;
				}
			}
		};
		t = new Thread() {
			public void run() {
				System.out.println("开始请求"+path);
				
				Message msg = new Message();
				
				try {
					list = analyzeXMLForHomepage.getRss(path);
					//System.out.println(path);
					List<CategoryCount> temp = analyzeXMLForCategoryTitleCount.getRss(getResources().getString(R.string.gettitlelistcount_url222)+categoryId+"&device=Android");
					//System.out.println("+++++++++++++"+(getResources().getString(R.string.gettitlelistcount_url222)+categoryId));
					category_count = temp.get(0).getCount();
					
					
					if(category_count>30 && category_count<60){
						footerButton.setText("次の"+(category_count-30)+"件を読み込む？");
						System.out.println("设置footerButton上的字为"+(category_count-30));
					} else {
						footerButton.setText("次の"+30+"件を読み込む？");
						System.out.println("设置footerButton上的字为30");
					}
					
					//System.out.println(getResources().getString(R.string.gettitlelistcount_url222)+categoryId);
					//System.out.println(getResources().getString(R.string.gettitlelistcount_url)+categoryId);
					if(list.size()!=0&&temp.size()!=0){
						System.out.println("得到具体某个category---->"+temp.get(0).getCategory()+","+temp.get(0).getCount());
						
						msg.what = HOMEPAGE_REQUEST_OK;
					}else{
						msg.what = HOMEPAGE_REQUEST_ERR;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					msg.what = 9;//请求超时
				} finally {
					handler.sendMessage(msg);
				}
				
				
				
				
			};
		};
		t.start();
	}
	
	/*private void getTitleCountThread(){
		new Thread(){
			public void run() {
				String tempUrl = getResources().getString(R.string.gettitlelist_category_url)+categoryId;
				try {
					list = analyzeXMLForHomepage.getRss(tempUrl);
					List<CategoryCount> temp = analyzeXMLForCategoryTitleCount.getRss(getResources().getString(R.string.gettitlelistcount_url)+categoryId);
					category_count =  temp.get(0).getCount();
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					
				}
			};
		}.start();
	}*/
	
	private void showNetBusy(){
		new AlertDialog.Builder(CategoryPage.this).setTitle(R.string.request_timeout)
			.setPositiveButton(R.string.determine, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if(t.isAlive()){
						t.interrupt();
					}
					category_progress.setVisibility(View.VISIBLE);
					category_refresh.setEnabled(false);
					category_refresh.setClickable(false);
					category_close.setEnabled(false);
					category_close.setClickable(false);
					refreshCategoryList();
				}
			})
			.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					openMenu();
				}
			}).create().show();
	}
	
	public void openMenu(){
		if(!menu_display){
			
			category_progress = layout.findViewById(R.id.category_list_progress);
			
			menuWindow.setAnimationStyle(R.style.PopupAnimation);
			menuWindow.showAtLocation(CategoryPage.this.getCurrentFocus(), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
			menuWindow.setFocusable(true);
			
			menuWindow.update();
			
			menu_display = true;
			if(dbService.getCount()==0){//当前数据库中没有数据
				//显示进度条************************************************************************
				flag = false;
				new Thread() {
					public void run() {
						Message message = new Message();
						try {
							categoryList = analyzeXMLForCategory.getRss(getCategoryUrl);
							if (categoryList.size() != 0) {
								message.what = 2;
								
							} else {
								
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							message.what = -2;
							System.out.println("刷新超时");
						} finally{
							
							handler.sendMessage(message);
						}
						
					};
				}.start();
			}else{
				//当前数据库中有数据，直接从数据库中读取
				flag = true;
				CategoryService service = new CategoryService(this);
				categoryList = service.getAll();
				Message msg = new Message();
				msg.what = 3;
				handler.sendMessage(msg);
			}
			
			
		}else{
			//如果当前已经为显示状态，则隐藏起来
			
			menuWindow.dismiss();
			menuWindow.setFocusable(false);
			menu_display = false;
			
		}
	}
	
	//刷新
	private void refreshCategoryList(){
		new Thread() {
			public void run() {
				try {
					categoryList = analyzeXMLForCategory.getRss(getCategoryUrl);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message message = new Message();
				if (categoryList.size() != 0) {
					message.what = 4;
					
				} else {
					message.what = -2;
				}
				handler.sendMessage(message);
			};
		}.start();
	}

	// 显示列表
	private void showList() {
		homePageAdapter = new HomePageAdapter(list, this);
		
		//setListAdapter(homePageAdapter);
		listView.setAdapter(homePageAdapter);
	}
	private void showCategoryList() {
		
		categoryAdapter = new CategoryAdapter(categoryList, CategoryPage.this);
		
		category_listview.setAdapter(categoryAdapter);
		category_progress.setVisibility(View.GONE);
		CategoryService service = new CategoryService(this);
		service.save(categoryList);//保存到数据库中
		
	}
	
	private void refreshShowCategoryList() {
		
		categoryAdapter = new CategoryAdapter(categoryList, CategoryPage.this);
		
		category_listview.setAdapter(categoryAdapter);
		category_progress.setVisibility(View.GONE);
		CategoryService service = new CategoryService(this);
		//service.save(categoryList);//更新到数据库
		service.update(categoryList);
		
	}
	//从数据库中读取数据并显示
	private void showCategoryListFromDB() {
		System.out.println("这是从数据库来的消息");
		categoryAdapter = new CategoryAdapter(dbService.getAll(), CategoryPage.this);
		
		category_listview.setAdapter(categoryAdapter);
		category_progress.setVisibility(View.GONE);
	}

	// 当点击某个Item时加载
	/*@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		News news = list.get(position);
		Intent intent = new Intent(this, NewsContent.class);
		Bundle bundle = new Bundle();
		bundle.putString("title", news.getTitle());
		bundle.putInt("id", news.getId());
		intent.putExtras(bundle);
		startActivity(intent);
	}*/
	
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(t!=null && t.isAlive()){
				t.interrupt();
				System.out.println("线程正在运行，强行中断");
			}
			if(t2!=null && t2.isAlive()){
				t2.interrupt();
				System.out.println("线程正在运行，强行中断");
			}
			if(t3!=null && t3.isAlive()){
				t3.interrupt();
				System.out.println("线程正在运行，强行中断");
			}
			CategoryPage.this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();
		if(!b){
			if(sp!=null){
				Editor editor = sp.edit();
				editor.clear();
				editor.commit();
			}
			System.out.println("开始销毁Activity");
			CloseUtil.closeActivity();
		}else{
			System.out.println("没有销毁Activity");
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		b = false;
	}
}
